<template>
  <view class="page">
    <u-sticky :offsetTop="0">
      <view class="head-tabs">
        <view class="tabs-wrap">
          <u-tabs
            :current="tabCurrent"
            :scrollable="true"
            :list="tabList"
            keyName="title"
            lineColor="#F49C0D"
            :lineWidth="40"
            :lineHeight="2"
            @click="tabClick"
            :itemStyle="{
              height: '50px',
              width: '20%',
              fontSize: '28rpx',
              color: '#333333',
            }"
            :activeStyle="{ fontWeight: 'bold', color: '#000000' }"
            :inactiveStyle="{}"></u-tabs>
        </view>
        <!-- 售后筛选 -->
        <!-- <view class="tabs-wrap-2" v-if="show_refund">
					<u-tabs :current="refund_tabCurrent" :scrollable="false" :list="refund_tabList" @click="refund_tabClick"
						keyName="title" lineColor="#CB0011" :lineWidth="28" :lineHeight="2"
						:itemStyle="{height: '50px',fontSize: '28rpx',color:'#666666'}"
						:activeStyle="{fontWeight: 'bold',color: '#000000' }"
						:inactiveStyle="{color: '#9695A3',fontWeight:'400',fontSize:'28rpx' }"></u-tabs>
					</u-tabs>
				</view> -->
      </view>
    </u-sticky>

    <view class="page-ctx">
      <view class="view-wrap">
        <view class="order-view" v-if="!show_refund">
          <view class="order-wrap">
            <view class="order-list">
              <view class="item" v-for="(item, index) in orders" :key="index">
                <view class="item-top flex-between">
                  <text class="order-sn">订单号：{{ item.orderNo }}</text>
                  <!-- <text v-if="item.if_pingjia==0 && item.status==4" class="status">待评价</text> -->
                  <text class="status">{{ item.statusInfo }}</text>
                </view>

                <view class="item-center" @click="toDetail(item)">
                  <view class="products-wrap">
                    <view class="product-list">
                      <view
                        class="product-item flex"
                        v-for="(product, index) in item.products"
                        :key="index">
                        <view class="poster-box">
                          <image :src="product.image" mode="aspectFill"></image>
                        </view>
                        <view class="info">
                          <view class="title-box">
                            <view class="title ellipsis-2">
                              {{ product.title }}
                            </view>
                          </view>
                          <view class="desc-box">
                            <view class="desc ellipsis-1">
                              {{ product.keyVals }}
                            </view>
                          </view>
                          <view class="price-box flex-between">
                            <view class="price-info">
                              {{ product.priceSale || 0 }}积分
                            </view>
                            <text class="num">x {{ product.num }}</text>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="item-bottom">
                  <view class="total-box">
                    <view class="price">实付款：￥{{ item.price }}</view>
                  </view>
                  <view class="btns flex">
                    <view
                      class="btn fit-text btn-detail"
                      @click="toDetail(item)">
                      订单详情
                    </view>
                    <view
                      v-if="item.ifCancel == 1"
                      class="btn fit-text btn-cancel"
                      @click="doCancel(item)">
                      取消订单
                    </view>
                    <view
                      v-if="item.ifPay == 1"
                      class="btn fit-text btn-pay"
                      @click="doPay(item)">
                      去支付
                    </view>
                    <view
                      v-if="item.ifDel == 1"
                      class="btn fit-text"
                      @click="doDelete(item)">
                      删除订单
                    </view>
                    <!-- <view v-if="item.is_allow_receive" class="btn fit-text" @click="toDetail(item)">
											查看物流
										</view> -->
                    <view
                      v-if="item.ifReceive == 1"
                      class="btn fit-text btn-pay"
                      @click="doReceive(item)">
                      确认收货
                    </view>
                    <!-- <view v-if="item.is_allow_review" class="btn fit-text btn-pay" @click="doReview(item)">
							评价
						</view> -->
                    <!-- <view v-if="item.is_allow_refund" class="btn fit-text btn-pay" @click="doRefund(item)">
							售后
						</view> -->
                  </view>
                </view>
              </view>
            </view>

            <view class="load-more-wrap" style="margin-top: 40rpx">
              <u-loadmore :status="loadmore_status" />
            </view>
          </view>
        </view>

        <view class="refund-view" v-if="show_refund">
          <refund_order_list ref="refund_order_list"></refund_order_list>
        </view>
      </view>
    </view>

    <w_bottom_safe height="40" />

    <order_cancel_pop
      data-title="订单取消"
      ref="order_cancel_pop"
      @confirm="update_order_info" />
    <order_delete_pop
      data-title="订单删除"
      ref="order_delete_pop"
      @confirm="confrimDelete" />
    <order_payment_methods_pop
      data-title="订单支付"
      ref="order_payment_methods_pop"
      @confirm="update_order_info" />
    <order_receive_pop
      data-title="订单确认收货"
      ref="order_receive_pop"
      @confirm="update_order_info" />
  </view>
</template>

<script>
import refund_order_list from "@/components/refund/refund_order_list.vue";

import order_cancel_pop from "@/components/order/order_cancel_pop.vue";
import order_delete_pop from "@/components/order/order_delete_pop.vue";
import order_payment_methods_pop from "@/components/order/order_payment_methods_pop.vue";
import order_receive_pop from "@/components/order/order_receive_pop.vue";

export default {
  components: {
    refund_order_list,

    //
    order_cancel_pop,
    order_delete_pop,
    order_payment_methods_pop,
    order_receive_pop,
  },
  data() {
    return {
      show_refund: false, //订单 售后切换
      //
      orders: [
        {
          orderNo: "111111",
          statusInfo: "1",
          products: [
            {
              title: "11111111",
              image: require("@/static/image/upload.png"),
              keyVals: "23",
              priceSale: 500,
              num: 1,
            },
          ],
        },
      ],
      order_select: {}, //
      count: 0,
      pagination: {
        page: 1,
        pageNum: 10,
      },
      loadmore_status: "loadmore", //loadmore  / loading / nomore

      statusNameMap: {
        1: "待支付", //已取消
        2: "待自提", //已取消
        3: "待评价",
        4: "已完成",
      },

      tabCurrent: 0,
      tabSelect: {
        title: "全部",
        value: 0,
      },
      tabList: [
        {
          title: "全部",
          value: 0,
        },
        {
          title: "待支付",
          value: 1,
        },
        {
          title: "待自提",
          value: 2,
        },
        {
          title: "待评价",
          value: 3,
        },

        {
          title: "已完成",
          value: 4,
        },
      ],

      // 售后相关
      refund_tabCurrent: 0,
      refund_tabSelect: {
        title: "申请售后",
        value: 0,
      },
      refund_tabList: [
        {
          title: "申请售后",
          value: 0,
        },
        {
          title: "处理中",
          value: 1,
        },
        {
          title: "已完成",
          value: 2,
        },
        // {
        // 	title: '已驳回',
        // 	value: 3,
        // },
      ],

      order_item: {},
    };
  },

  computed: {},

  onLoad(option) {
    console.log("option", option);
    if (option.status) {
      this.tabSelect = this.tabList.find((v) => v.value == option.status);
      this.tabCurrent = this.tabList.findIndex((v) => v.value == option.status);
    }
  },
  onShow() {
    //this.initQuery();
    //this.setView();
  },
  onHide() {},
  onPullDownRefresh() {},
  onReachBottom() {
    this.loadMore();
  },
  methods: {
    loadMore() {
      if (this.loadmore_status == "loadmore") {
        this.loadmore_status = "loading";
        this.pagination.page++;
        this.query_order();
      }
    },
    initQuery() {
      this.orders = [];
      this.pagination.page = 1;
      this.loadmore_status = "loadmore";
    },
    setView() {
      this.query_order();
    },

    query_order() {
      this.query_order_list();

      // if (this.tabSelect.value != 6) {

      // } else {
      // 	this.query_refund_list();
      // }
    },

    query_order_list() {
      this.$api({
        url: "/service.php",
        method: "get",
        data: {
          action: "orders_lists",
          ...this.pagination,
          scene: this.tabSelect.value, //0全部 1待支付 2待发货 3待收货 4待评价 5已评价 -1无效
          type: 2, //订单类型：0-全部 1-积分订单 2-商城订单
        },
      }).then((res) => {
        if (res.code == 200) {
          this.count = res.data.count;
          let list = res.data.list;
          // res.data.forEach(v => {
          // 	// v.count_down_pay_end_time = v.pay_end_time > 0 ? v.pay_end_time * 1000 : 0
          // 	this.handleOrderActions(v)
          // })
          // this.format_order_view_info(res.data)
          this.orders = this.orders.concat(list);
          this.loadmore_status =
            this.count > this.orders.length ? "loadmore" : "nomore";
        }
      });
    },

    query_refund_list() {
      this.$api({
        url: "/service.php",
        method: "get",
        data: {
          action: "orders_lists",
          ...this.pagination,
          scene: this.tabSelect.value, //0全部 1待支付 2待发货 3待收货 4待评价 5已评价 -1无效
        },
      }).then((res) => {
        if (res.code == 200) {
          this.count = res.data.count;
          // res.data.forEach(v => {
          // 	// v.count_down_pay_end_time = v.pay_end_time > 0 ? v.pay_end_time * 1000 : 0
          // 	this.handleOrderActions(v)
          // })

          this.format_order_view_info(res.data);

          this.orders = this.orders.concat(res.data);
          this.loadmore_status =
            res.data.count > this.orders.length ? "loadmore" : "nomore";
        }
      });
    },

    //format_order_view_info
    format_order_view_info(list) {
      list.forEach((v) => {
        let status = v.status;
        let status_info = v.status_info;
        //订单状态
        v.statusText = this.statusNameMap[status];
        if (status_info == "订单已取消") {
          v.statusText = "订单已取消";
        }

        //允许操作类状态
        v.is_allow_cancel = v.if_cancel == 1; // (status == -5 && status_info == '待支付'); //取消订单
        v.is_allow_pay = v.if_pay == 1; //status == -5 && status_info == '待支付' //去支付
        v.is_allow_delete = v.if_del == 1; //status == -1; //删除订单
        v.is_allow_receive = status == 3; //确认收货
        v.is_allow_review = v.if_pingjia == 1; ///false && status == 4; //评价
        v.is_allow_refund = v.if_shouhou == 1; // false //申请售后

        //结果类状态
        v.is_finish_pay = false; //是否已被支付
        v.is_finish_hexiao = false; //是否已被核销
        v.is_finish_cancel = false; //是否已被取消
      });
    },

    //处理订单操作
    handleOrderActions(v) {
      let status = v.status;
      //订单状态
      v.statusText = this.statusNameMap[status];
      //订单操作
      v.is_allow_pay = status == 1;
      // v.is_allow_cancel = status == 1 || status == 2;
      v.is_allow_cancel = v.is_allow_cancel > 0;
      // v.is_allow_refund = status == 1;
    },

    tabClick(e) {
      this.$log("tab e", e);

      // if (e.value == 6) {
      // 	this.show_refund = true;
      // 	this.$nextTick(() => {
      // 		this.$refs.refund_order_list.init(this.refund_tabSelect);
      // 	})

      // } else {
      // 	this.show_refund = false;
      // 	this.tabSelect = e
      // 	this.initQuery();
      // 	this.setView();
      // }

      this.tabSelect = e;
      this.initQuery();
      this.setView();
    },

    toDetail(item) {
      this.toRoute({
        path: "/order-detail",
        query: {
          id: item.id,
        },
      });
    },

    // 微信支付
    use_weixin_pay() {
      this.showLoading({
        title: "支付信息请求中",
        disClose: true,
      });

      let order_id = this.order_select.id;
      this.$api({
        url: "/service.php",
        method: "get",
        data: {
          action: "pay_weixin",
          orderId: order_id,
          orderType: 1,
        },
      }).then((res) => {
        let data = res.data || {};
        // this.hideLoading();
        // this.$alert(res);
        // if (this.is_test_pay_order) {
        // 	this.toPaySuccess()
        // 	return
        // }

        if (res.code == 200) {
          uni.requestPayment({
            provider: "wxpay",
            timeStamp: String(data.timeStamp),
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: (res) => {
              console.log("支付成功", res);
              this.toPayResult();
            },
            fail: (err) => {
              this.$alert("支付失败");
              setTimeout(() => {
                this.toPayFail();
              }, 1000);
              // console.log('支付失败', err)
            },
            complete: () => {
              this.hideLoading();
            },
          });
        } else {
          this.$alert(res);
        }

        // #ifdef H5
        this.hideLoading();
        // #endif
      });
    },

    // 余额支付
    use_yue_pay() {
      let order_id = this.order_select.id;
      this.$api({
        url: "/service.php",
        method: "get",
        data: {
          action: "pay_balance",
          order_id: order_id,
        },
      }).then((res) => {
        this.$alert(res);
        let data = res.data;
        if (res.code == 200) {
          if (res.is_over == 1) {
            this.toPayResult(1);
          } else {
            this.toPayResult(0);
          }
        } else {
          this.$alert(res.message);
          setTimeout(() => {
            this.toPayFail();
          }, 1000);
        }
      });
    },

    toPaySuccess() {
      this.toPayResult(1);
    },
    toPayFail() {
      // this.toPayResult(0)
    },
    toPayResult(is_pay = 0) {
      this.toRoute({
        path: "/payment-success",
        query: {
          order_id: this.order_select.id,
          type: "order",
          is_pay: is_pay,
        },
        // mode: 'redirectTo'
      });
    },

    doCancel(item) {
      this.$refs.order_cancel_pop.init(item);
    },
    doDelete(item) {
      this.$refs.order_delete_pop.init(item);
    },
    confrimDelete(id) {
      let index = this.orders.findIndex((v) => v.id == id);
      this.orders.splice(index, 1);
    },

    doPay(item) {
      this.$refs.order_payment_methods_pop.init(item);
    },
    confrimPay(item) {
      if (item == 1) {
        //余额支付
        this.use_yue_pay();
      } else {
        //微信支付
        this.use_weixin_pay();
      }
      // this.changeOrderStatus(2)
    },

    doReceive(item) {
      // this.$refs.order_receive_pop.init(item)

      // #ifdef MP-WEIXIN
      this.order_item = item;
      this.mix_throttle(this.weixin_receive);
      // #endif

      // #ifndef MP-WEIXIN
      this.other_receive(item);
      // #endif
    },

    //微信收货
    weixin_receive() {
      let item = this.order_item;
      console.log("确认收货 weixin_receive");
      console.log("确认收货 wx.openBusinessView", wx.openBusinessView);
      //拉起确认收货组件
      if (wx.openBusinessView) {
        let transaction_id = "";
        if (item.shouhuoLishui && item.shouhuoLishui.length) {
          transaction_id = item.shouhuoLishui[0].transactionId || "";
        }
        console.log("确认收货 transaction_id", transaction_id);

        wx.openBusinessView({
          businessType: "weappOrderConfirm",
          extraData: {
            merchant_id: "", //'1230000109',用户交易商户号
            merchant_trade_no: "", //'1234323JKHDFE1243252',商户订单号
            transaction_id: transaction_id, //'420123123123123123123' 	用户交易单号
          },
          success: (params) => {
            console.log("success params", params);
            //dosomething
            // let demo_params = {
            // 	errCode: 0,
            // 	errMsg: "openBusinessView:ok",
            // 	extraData: {
            // 		status: 'success',//"success":用户确认收货成功;"fail":用户确认收货失败;"cancel":用户取消
            // 		errormsg: '',
            // 		req_extradata: {

            // 		}
            // 	},
            // }
            if (
              params &&
              params.extraData &&
              params.extraData.status == "success"
            ) {
              this.do_confirm_receive(item);
            }
          },
          fail: (params) => {
            console.log("fail params", params);
            //dosomething
            this.$alert(params.errMsg);
          },
          complete: (params) => {
            console.log("complete params", params);
            //dosomething
          },
        });
      } else {
        //引导用户升级微信版本
      }
    },
    //其他收货
    other_receive(item) {
      console.log("确认收货 other_receive");

      this.$refs.order_receive_pop.init(item);
    },
    //
    do_confirm_receive(item) {
      this.$api({
        url: "/service.php",
        method: "get",
        data: {
          action: "orders_shouhuo",
          id: item.id,
        },
      }).then((res) => {
        this.$alert(res);
        if (res.code == 200) {
          this.update_order_info(item.id);
        }
      });
    },

    doReview(item) {},
    doRefund(item) {},

    // 下列操作后需要改变订单状态码 并更新列表的订单按钮操作
    //取消订单
    //支付订单
    //订单售后
    //确认收货等操作后
    changeOrderStatus(status) {
      let item = this.order_select;
      let index = this.orders.findIndex((v) => v.id == item.id);
      //全部订单切换状态  其它隐藏
      if (this.tabSelect.value == 0) {
        //全部
        item.status = status;
        if (item.status == -5) {
          item.status_info = "订单已取消"; // 待支付  -> 订单已取消
        }
        this.format_order_view_info([item]);
        this.orders.splice(index, 1, item);
      } else {
        this.orders.splice(index, 1);
      }
    },

    //
    refund_tabClick(item) {
      this.refund_tabSelect = item;
      this.$nextTick(() => {
        this.$refs.refund_order_list.init(this.refund_tabSelect);
      });
    },

    // 更新订单信息
    update_order_info(id) {
      let index = this.orders.findIndex((v) => v.id == id);
      let item = this.orders[index];

      if (this.tabSelect.value != 0) {
        //不是全部订单
        this.orders.splice(index, 1);
        return;
      }

      this.$api({
        url: "/service.php",
        method: "get",
        data: {
          action: "orders_detail",
          id: id,
        },
      }).then((res) => {
        if (res.code == 200) {
          let data = res.data;

          let new_item = {
            ...item,
            ifCancel: data.ifCancel,
            ifComment: data.ifComment,
            ifCommented: data.ifCommented,
            ifDel: data.ifDel,
            ifHx: data.ifHx,
            ifPay: data.ifPay,
            ifReceive: data.ifReceive,
            orderStatus: data.orderStatus,
            statusInfo: data.statusInfo,
          };

          this.orders.splice(index, 1, new_item);
        }
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background: #f8f8f8;
}
</style>

<style lang="scss" scoped>
// ::v-deep .tabs-wrap .u-tabs__wrapper__nav__item {
// 	padding: 0 8rpx;
// }
.page {
}

.page-ctx {
  padding: 24rpx 32rpx;
}

.head-tabs {
  // position: fixed;
  // z-index: 10;
  // top: 0;
  // left: 0;
  // right: 0;
  background: #fff;
}

.tabs-wrap {
  padding-top: 0;
  box-shadow: 0rpx -10rpx 10rpx 1rpx rgba(0, 0, 0, 0.08);
  background: #f6f6f6;
  background: #fff;
  border-bottom: 1rpx solid #eee;

  .tabs {
    .tab-item {
      height: 100rpx;
      line-height: 100rpx;
      position: relative;
      // padding: 25rpx 0;
      text-align: center;
      flex: 1;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #222222;

      &.active {
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        font-size: 28rpx;
        color: #222222;

        &::after {
          content: "";

          position: absolute;
          z-index: 2;
          bottom: 0;
          left: 50%;
          transform: translate(-50%);
          width: 40rpx;
          height: 6rpx;
          background: #44c4be;
          border-radius: 0rpx 0rpx 0rpx 0rpx;
        }
      }
    }
  }
}

// 退款订单
.order-wrap {
  .order-list {
    .item {
      margin-bottom: 24rpx;
      background: #ffffff;
      // box-shadow: 0rpx 0rpx 16rpx 2rpx rgba(0, 0, 0, 0.08);
      border-radius: 16rpx 16rpx 16rpx 16rpx;

      padding: 32rpx 24rpx;
      margin-bottom: 20rpx;
      background: #ffffff;

      .item-top {
        padding: 0 0;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #666666;

        .order-sn {
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: #666666;
        }

        .status {
          font-family: PingFang SC, PingFang SC;
          font-weight: bold;
          font-size: 24rpx;
          color: #f40d0d;
        }
      }

      .item-center {
        // border-top: 1rpx solid #eee;
      }

      .item-bottom {
        // border-top: 1rpx solid #eee;
        // padding: 20rpx 0;

        .total-box {
          text-align: right;

          .price {
            text-align: right;
            font-family: PingFang SC, PingFang SC;
            font-weight: bold;
            font-size: 28rpx;
            color: #000000;
          }
        }

        .btns {
          margin-top: 34rpx;
          flex: 1;
          justify-content: flex-end;
          overflow: hidden;
          flex-wrap: wrap;

          .btn {
            margin-left: 20rpx;
            width: 160rpx;
            height: 64rpx;
            line-height: 64upx;
            text-align: center;
            background: #f6f6f6;
            border-radius: 8rpx 8rpx 8rpx 8rpx;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 24rpx;
            color: #333333;

            &.btn-detail {
            }

            &.btn-pay {
              background: #f49c0d;
              color: #ffffff;
            }

            &.btn-reviews {
            }

            &.btn-cancel {
            }
          }
        }
      }
    }
  }

  .products-wrap {
    padding: 0 0;

    .product-list {
      .product-item {
        padding: 34rpx 0 36upx;

        & + .product-item {
          border-top: 1rpx solid #eee;
        }

        .poster-box {
          width: 176rpx;
          height: 176rpx;
          border-radius: 8rpx;
          overflow: hidden;

          image {
            width: 100%;
            height: 100%;
          }
        }

        .info {
          flex: 1;
          overflow: hidden;
          padding-left: 24rpx;

          .title-box {
          }

          .title {
            font-family: PingFang SC, PingFang SC;
            font-weight: bold;
            font-size: 28rpx;
            color: #222222;
            line-height: 1.5;
          }

          .desc-box {
            margin-top: 14rpx;

            .desc {
              font-family: PingFang SC, PingFang SC;
              font-weight: 400;
              font-size: 24rpx;
              color: #000000;
            }
          }

          .price-box {
            margin-top: 18rpx;

            .price-info {
              font-weight: bold;
              font-size: 28rpx;
              color: #e23410;
            }

            .num {
              font-weight: bold;
              font-size: 28rpx;
              color: #000000;
            }
          }
        }
      }
    }
  }
}
</style>
